<template>

  <el-autocomplete
    style="width:100%;"
    v-model="state"
    :fetch-suggestions="queryAsync"
    placeholder="请选择部门"
    @select="handleSelect"
    value="id"
    valueKey="name"
    :debounce="500">
  </el-autocomplete>

</template>
<script>

  import axios from "@/util/axios";

  const deps = {};

  export default {

    props:['value','url'],

    watch:{

      value(newVal){
        if(this.__prev_def)
          return;
        if(!newVal){
          this.state = '';
        } else {
          if(deps[newVal]){
            this.prevChange();
            this.state = deps[newVal];
          }else{
           axios.get('/api/v1/suser/dep/get',{params:{id:newVal}})
           .then(({data})=>{
            this.prevChange();
            this.state = data.name;
            deps[newVal] = data.name;
           });
          }
        }
      },

      state(newVal){
        if(this.__prev_def)
          return;
        this.$emit('input',undefined);
      }

    },

    data() {
      return {
        id:'',
        depId:'',
        depName:'',
        state: '',
        __prev_def:false,
      };
    },
    methods: {

      queryAsync(query, cb) {
        axios.get('/api/v1/suser/dep/search',{params:{name:query||''}})
        .then(({data}) => {
          cb(data);
        });
      },

      prevChange(){
        this.__prev_def = true;
        setTimeout( ()=> this.__prev_def = false,500);
      },

      handleSelect(item) {
        this.prevChange();
        this.$emit('input',item.id);
      },
    }
  }
</script>
